package code;

import java.util.*;

public class SpecialDeep4_3_day15 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public static void main(String[] args) {
        int[] nums = new int[]{1,2,3,4,5,1000,7,8};
        TreeNode treeNode= createTree(nums);
        printTree(treeNode);
        createList(treeNode);
    }
    public static ListNode[] createList(TreeNode root) {
        List<ListNode> result = new ArrayList<>();
        Deque<TreeNode> deque= new LinkedList<>();
        deque.addLast(root);
        while (!deque.isEmpty()) {
            int size = deque.size();
            ListNode list= new ListNode();
            ListNode p=list;
            for(int i=0;i<size;i++) {

                TreeNode node = deque.pop();
                if(node.left != null) {
                    deque.addLast(node.left);
                }
                if(node.right != null) {
                    deque.addLast(node.right);
                }
                p.next = new ListNode(node.val);
                p=p.next;
            }
            result.add(list.next);
        }
        ListNode[] node_res=new ListNode[result.size()];
        for(int i=0;i<result.size();i++) {
            node_res[i]=result.get(i);
        }
        return node_res;
    }
    public static TreeNode createTree(int[] nums) {

        Deque<TreeNode> deque= new LinkedList<>();
        TreeNode root = new TreeNode(nums[0]);
        deque.push(root);
        int i = 1;
        while (!deque.isEmpty()) {
            if(i==nums.length){
              return root;
            }
            TreeNode node = deque.pop();
            node.left = new TreeNode(nums[i]);
            deque.push(node.left);
            i++;
            if(i==nums.length){
                return root;
            }
            node.right = new TreeNode(nums[i]);
            deque.push(node.right);
            i++;
        }
     return root;
    }
    public static void printTree(TreeNode root) {
        System.out.println(root.val);
        if (root.left != null) {
            printTree(root.left);
        }
        if (root.right != null) {
            printTree(root.right);
        }
    }
}
